package stardust.product.utils.excel_image;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;


public class ExcelToImage
{
  
  public static int[][] parseImage(String file, int scale) throws IOException
  {
    BufferedImage img = ImageIO.read(new File(file));
    
    int w = img.getWidth();
    int h = img.getHeight();
    
    int woffset = w / scale;
    int hoffset = h / scale;
    
    int[][] colors = new int[woffset][hoffset];
    
    for (int x = 0; x < colors.length; x += scale)
    {
      for (int y = 0; y < colors[x].length; y += scale)
      {
        colors[x][y] = img.getRGB(x, y);
      }
    }
    
    return colors;
  }
  
  public static void main(String[] args) throws IOException {
    int[][] colors = parseImage("1.jpg", 5);
    
    try {
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet();
        HSSFPalette palette = wb.getCustomPalette();
        
        HSSFRow row;
        HSSFCell cell;
        
        short offset = 512;
        
        for (int i = 0; i < colors.length; i++)
        {
          row = sheet.createRow(i);
          row.setHeight((short) (120));
          
          for (int j = 0; j < colors[i].length; j++)
          {
            sheet.setColumnWidth(j, (int) (120 * 2));
            
            palette.setColorAtIndex(offset++, (byte) new Color(colors[i][j]).getRed(), (byte) new Color(colors[i][j]).getGreen(), (byte) new Color(colors[i][j]).getBlue());
            
            cell = row.createCell(j);
            
            HSSFCellStyle cs = wb.createCellStyle();
            cs.setFillForegroundColor(offset);
            cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            
            cell.setCellStyle(cs);
          }
        }
        
        FileOutputStream fileOut = new FileOutputStream("a.xls");
        wb.write(fileOut);
        fileOut.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
  }
  
}
